//
//  ZXUIImageExtension.swift
//  ExtensionTest
//
//  Created by ZX on 2025/2/6.
//

import UIKit

public enum ZXImageGradientType {
    case topToBottom
    case leftToRight
    case topLeftToBottomRight
    case topRightToBottomLeft
}


public extension UIImage{
    convenience init?(_ color: HexColorConvertible, _ alpha: CGFloat = 1, _ size: CGSize = CGSize(width: 1, height: 1)) {
        let color = color.convertToColor()
        // Alpha 处理优化：将传入 alpha 与颜色原有 alpha 相乘
        let combinedAlpha = color.cgColor.alpha * alpha
        let combinedColor = color.withAlphaComponent(combinedAlpha).cgColor
        
        // 尺寸合法性检查（可选）
        guard size.width > 0 && size.height > 0 else { return nil }
        
        // 使用现代渲染器 API
        let renderer = UIGraphicsImageRenderer(size: size)
        let image = renderer.image { context in
            context.cgContext.setFillColor(combinedColor)
            context.fill(CGRect(origin: .zero, size: size))
        }
        
        guard let cgImage = image.cgImage else { return nil }
        // 直接通过 UIImage 初始化（不再需要 CGImage 中间转换）
        self.init(cgImage: cgImage)
    }
    
    convenience init?(_ colors:[HexColorConvertible], _ imgSize: CGSize = CGSize(width: 1, height: 1), _ type:ZXImageGradientType = .leftToRight,_ alpha: CGFloat = 1) {
        if colors.count == 1, let color = colors.first {
            self.init(color)
            return
        }
        let colorArr : [UIColor] = colors.map{.init($0)}
        
        // 渐变的颜色数组和位置数组
        let gradientColors = colorArr.map { $0.cgColor }
        
        // 绘制渐变
        var startPoint: CGPoint = CGPoint(x: 0, y: 0)
        var endPoint : CGPoint = CGPoint(x: 0, y: 0)
        
        switch type {
        case .leftToRight:
            startPoint = CGPoint(x: 0, y: 0.5)
            endPoint = CGPoint(x: 1, y: 0.5)
        case .topToBottom:
            startPoint = CGPoint(x: 0.5, y: 0)
            endPoint = CGPoint(x: 0.5, y: 1)
        case .topLeftToBottomRight:
            startPoint = CGPoint(x: 0, y: 0)
            endPoint = CGPoint(x: 1, y: 1)
        case .topRightToBottomLeft:
            startPoint = CGPoint(x: 1, y: 0)
            endPoint = CGPoint(x: 0, y: 1)
        }
        let gradientLayer = CAGradientLayer()
        gradientLayer.frame = CGRect(origin: CGPoint(x: 0, y: 0), size: imgSize)
        gradientLayer.colors = gradientColors
        
        gradientLayer.startPoint = startPoint
        gradientLayer.endPoint = endPoint
        
        // 使用UIGraphicsImageRenderer创建图片
        let renderer = UIGraphicsImageRenderer(bounds: gradientLayer.bounds)
        let image = renderer.image { _ in
            gradientLayer.render(in: UIGraphicsGetCurrentContext()!)
        }
        
        guard let cgImage = image.cgImage else { return nil }
        // 直接通过 UIImage 初始化（不再需要 CGImage 中间转换）
        self.init(cgImage: cgImage)
    }
}



@available(*, deprecated, message: "This function is deprecated. Use newFunction instead.")
public extension UIImage {
    class func c(_ color:UIColor, _ size:CGSize = .init(width: 375, height: 375), _ alpha: CGFloat = 1) -> UIImage {
        let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        UIGraphicsBeginImageContext(size)
        let context = UIGraphicsGetCurrentContext()!
        context.setFillColor(color.cgColor)
        context.setAlpha(alpha)
        context.fill(rect)
        
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsGetCurrentContext()
        return image!
    }
    
    class func c(_ colors:[Any], _ imgSize: CGSize, _ type:ZXImageGradientType = .leftToRight, _ alpha: CGFloat = 1) -> UIImage {
        var colorArr : [UIColor] = []
        if let colors = colors as? [UIColor] {
            colorArr = colors
        }else{
            for color in colors {
                colorArr.append(UIColor.c(color, alpha))
            }
        }
        if colorArr.count == 1, let color = colorArr.first {
            return self.c(color, imgSize)
        }
        // 渐变的颜色数组和位置数组
        let gradientColors = colorArr.map { $0.cgColor }
        
        // 绘制渐变
        var startPoint: CGPoint = CGPoint(x: 0, y: 0)
        var endPoint : CGPoint = CGPoint(x: 0, y: 0)
        
        switch type {
        case .leftToRight:
            startPoint = CGPoint(x: 0, y: 0.5)
            endPoint = CGPoint(x: 1, y: 0.5)
        case .topToBottom:
            startPoint = CGPoint(x: 0.5, y: 0)
            endPoint = CGPoint(x: 0.5, y: 1)
        case .topLeftToBottomRight:
            startPoint = CGPoint(x: 0, y: 0)
            endPoint = CGPoint(x: 1, y: 1)
        case .topRightToBottomLeft:
            startPoint = CGPoint(x: 1, y: 0)
            endPoint = CGPoint(x: 0, y: 1)
        }
        let gradientLayer = CAGradientLayer()
        gradientLayer.frame = CGRect(origin: CGPoint(x: 0, y: 0), size: imgSize)
        gradientLayer.colors = gradientColors
        
        gradientLayer.startPoint = startPoint
        gradientLayer.endPoint = endPoint
        
        // 使用UIGraphicsImageRenderer创建图片
        let renderer = UIGraphicsImageRenderer(bounds: gradientLayer.bounds)
        let image = renderer.image { _ in
            gradientLayer.render(in: UIGraphicsGetCurrentContext()!)
        }
        
        
        return image
    }
    
    ///
    func rounded(_ cornerRadius: UIRectCorner = .allCorners,_ cornerRadii: CGFloat = 10) -> UIImage {
        let rect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)
        UIGraphicsBeginImageContextWithOptions(self.size, false, UIScreen.main.scale)
        
        var value = cornerRadii
        if cornerRadii == 0 {
            value = size.height/2
        }
        UIBezierPath.init(roundedRect: rect, byRoundingCorners: cornerRadius, cornerRadii: CGSize(width: value, height: value)).addClip()
        self.draw(in: rect)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image!
    }
}
